<?php

class Reservations_RequestAction extends SrsReservationsBaseAction
{
	public function getCredentials()
	{
		return 'reservations.request';
	}

	public function executeRead(AgaviRequestDataHolder $rd)
	{
		$hall = $this->getTable('Hall')->find($rd->getParameter('hall'));

		if (!$hall instanceof Hall) return $this->forward404();

		$this->setAttribute('hall', $hall);

  	return 'Input';
	}

	public function executeWrite(AgaviRequestDataHolder $rd)
	{
		$hall = (int)$rd->getParameter('hall');
		$r    = $rd->getParameter('reservation');

		$from = strtotime($r['date'] . ' ' . $r['from'] . ':00');
		$to   = strtotime($r['date'] . ' ' . $r['to'] . ':00');

		foreach (Reservation::findOverlapping($hall, $from, $to) as $reservation)
		{
			if ($reservation->status !== 'new')
			{
				$this->addError('overlapping', 'reservation[period]', sprintf(
					'Podany termin jest już zajęty (od %s do %s).', date('H:i', $reservation->fromTime), date('H:i', $reservation->toTime)
				));

      	return 'Error';
			}
		}

		$reservation = new Reservation();
		$reservation->fromArray(array(
			'hallId'      => $hall,
			'creatorId'   => $this->context->getUser()->getCurrentUser()->id,
			'fromTime'    => $from,
			'toTime'      => $to,
			'department'  => $r['department'],
			'branch'      => $r['branch'],
			'year'        => $r['year'],
			'description' => $r['description'],
			'subject'     => $r['subject'],
			'lecturer'    => $r['lecturer'],
		));
		$reservation->save();

  	return 'Success';
	}
}